package com.iceframework.core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.net.ssl.SSLContext;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

public class HttpClientUtils {

	public static String doGet(String url, Map<String, String> param) {

		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);

			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String doGet(String url, Map<String, String> headers, Map<String, String> param) {

		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			headers.forEach((k, v) -> {
				httpGet.addHeader(k, v);
			});
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String doGet(String url) {
		return doGet(url, null);
	}

	public static String doPost(String url, Map<String, String> param) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建参数列表
			if (param != null) {
				List<NameValuePair> paramList = new ArrayList<>();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, param.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return resultString;
	}

	public static String doPost(String url, Map<String, String> headers, Map<String, String> param) {

		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			headers.forEach((k, v) -> {
				httpPost.addHeader(k, v);
			});
			// 创建参数列表
			if (param != null) {
				List<NameValuePair> paramList = new ArrayList<>();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, param.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String doPost(String url) {
		return doPost(url, null);
	}

	public static String doPostJson(String url, String jsonParams) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建请求内容
			StringEntity entity = new StringEntity(jsonParams, ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return resultString;
	}

	/** Https **/

	/**
	 * 用来解析https
	 * 
	 * @return
	 */
	public static CloseableHttpClient createSSLClientDefault() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		}
		return HttpClients.createDefault();
	}

	/**
	 * 设置信任自签名证书
	 * 
	 * @param keyStorePath 密钥库路径
	 * @param keyStorepass 密钥库密码
	 * @return
	 */
	public static CloseableHttpClient custom(String keyStorePath, String keyStorepass) {
		SSLContext sc = null;
		CloseableHttpClient client = null;
		FileInputStream instream = null;
		KeyStore trustStore = null;
		try {
			trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			instream = new FileInputStream(new File(keyStorePath));
			trustStore.load(instream, keyStorepass.toCharArray());
			// 相信自己的CA和所有自签名的证书
			sc = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
			// 如果密码为空，则用"nopassword"代替
			// SSLContext sslcontext = custom("D:\\keys\\wsriakey", "tomcat");

			// 设置协议http和https对应的处理socket链接工厂的对象
			Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
					.register("http", PlainConnectionSocketFactory.INSTANCE)
					.register("https", new SSLConnectionSocketFactory(sc)).build();
			PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
					socketFactoryRegistry);
			HttpClients.custom().setConnectionManager(connManager);

			// 创建自定义的httpclient对象
			client = HttpClients.custom().setConnectionManager(connManager).build();

		} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException
				| KeyManagementException e) {
			e.printStackTrace();
		} finally {
			try {
				instream.close();
			} catch (IOException e) {
			}
		}
		return client;
	}

	/**
	 * https请求 get
	 * 
	 * @throws Exception
	 */
	public static String doGetHttps(String url) throws Exception {
		CloseableHttpClient httpclient = null;
		if (StringUtils.startsWith(url, "https")) {
			httpclient = createSSLClientDefault();
		} else {
			httpclient = HttpClients.createDefault();
		}
		HttpGet httpget = new HttpGet(url);
		HttpResponse response = httpclient.execute(httpget);
		HttpEntity entity = response.getEntity();
		String html = EntityUtils.toString(entity, "UTF-8");
		httpclient.close();
		return html;
	}

	/**
	 * @param keyStorePath
	 * @param keyStorepass
	 * @param url          资源地址
	 * @param map          参数列表
	 * @param encoding
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String doPostHttps(String keyStorePath, String keyStorepass, String url, Map<String, String> map,
			String encoding) throws ClientProtocolException, IOException {
		String body = "";
		// 创建post方式请求对象
		HttpPost httpPost = new HttpPost(url);

		// 装填参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		if (map != null) {
			for (Entry<String, String> entry : map.entrySet()) {
				nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		// 设置参数到请求对象中
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

		// 设置header信息
		// 指定报文头【Content-type】、【User-Agent】
		httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
		httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

		// 执行请求操作，并拿到结果（同步阻塞）
		CloseableHttpResponse response = custom(keyStorePath, keyStorepass).execute(httpPost);
		// 获取结果实体
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			// 按指定编码转换结果实体为String类型
			body = EntityUtils.toString(entity, encoding);
		}
		EntityUtils.consume(entity);
		// 释放链接
		response.close();
		return body;
	}

	/**
	 * post
	 * 
	 * @throws Exception
	 */
	public static String doPostHttps(String keyStorePath, String keyStorepass, String url, Map<String, String> params)
			throws Exception {
		CloseableHttpClient httpclient = custom(keyStorePath, keyStorepass);
		HttpPost httppost = new HttpPost(url);

		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			formparams.add(new BasicNameValuePair(key, params.get(key)));
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);

		httppost.setEntity(entity);

		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity1 = response.getEntity();
		String html = EntityUtils.toString(entity1, "UTF-8");
		httpclient.close();
		return html;
	}

	/**
	 * Https Post Json
	 * 
	 * @param keyStorePath
	 * @param keyStorepass
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String doPostHttpsJson(String keyStorePath, String keyStorepass, String url, String jsonParams)
			throws Exception {
		CloseableHttpClient httpclient = custom(keyStorePath, keyStorepass);
		HttpPost httppost = new HttpPost(url);
		StringEntity entity = new StringEntity(jsonParams, "utf-8");
		entity.setContentType("application/json");
		entity.setContentEncoding("UTF-8");
		httppost.setEntity(entity);

		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity1 = response.getEntity();
		String html = EntityUtils.toString(entity1, "UTF-8");
		httpclient.close();
		return html;
	}

	/**
	 * Https Post Json
	 * 
	 * @param keyStorePath
	 * @param keyStorepass
	 * @param url
	 * @param params
	 * @param header
	 * @return
	 * @throws Exception
	 */
	public static String doPostHttpsJson(String keyStorePath, String keyStorepass, String url, String jsonParams,
			Map<String, String> header) throws Exception {
		CloseableHttpClient httpclient = custom(keyStorePath, keyStorepass);
		HttpPost httppost = new HttpPost(url);
		StringEntity entity = new StringEntity(jsonParams, "utf-8");
		entity.setContentType("application/json");
		entity.setContentEncoding("UTF-8");
		httppost.setEntity(entity);
		header.forEach((k, v) -> {
			httppost.setHeader(k, v);
		});

		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity1 = response.getEntity();
		String html = EntityUtils.toString(entity1, "UTF-8");
		httpclient.close();
		return html;
	}

	/**
	 * post
	 * 
	 * @throws Exception
	 */
	public static String doPostHttps(String url, Map<String, String> params) throws Exception {
		CloseableHttpClient httpclient = null;
		if (StringUtils.startsWith(url, "https")) {
			httpclient = createSSLClientDefault();
		} else {
			httpclient = HttpClients.createDefault();
		}
		HttpPost httppost = new HttpPost(url);

		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			formparams.add(new BasicNameValuePair(key, params.get(key)));
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);

		httppost.setEntity(entity);

		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity1 = response.getEntity();
		String html = EntityUtils.toString(entity1, "UTF-8");
		httpclient.close();
		return html;
	}

	public static String doPostHttps(String url, Map<String, String> header, Map<String, String> params)
			throws Exception {
		CloseableHttpClient httpclient = null;
		if (StringUtils.startsWith(url, "https")) {
			httpclient = createSSLClientDefault();
		} else {
			httpclient = HttpClients.createDefault();
		}
		HttpPost httppost = new HttpPost(url);

		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			formparams.add(new BasicNameValuePair(key, params.get(key)));
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);

		httppost.setEntity(entity);
		header.forEach((k, v) -> {
			httppost.setHeader(k, v);
		});

		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity1 = response.getEntity();
		String html = EntityUtils.toString(entity1, "UTF-8");
		httpclient.close();
		return html;
	}

	/**
	 * post
	 * 
	 * @throws Exception
	 */
	public static String doPostHttpsJson(String url, String jsonParams) throws Exception {
		CloseableHttpClient httpclient = null;
		if (StringUtils.startsWith(url, "https")) {
			httpclient = createSSLClientDefault();
		} else {
			httpclient = HttpClients.createDefault();
		}
		HttpPost httppost = new HttpPost(url);
		StringEntity entity = new StringEntity(jsonParams, "utf-8");
		entity.setContentType("application/json");
		entity.setContentEncoding("UTF-8");
		httppost.setEntity(entity);

		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity1 = response.getEntity();
		String html = EntityUtils.toString(entity1, "UTF-8");
		httpclient.close();
		return html;
	}

	public static String postJsonHttps(String url, Map<String, String> header, String jsonParams) throws Exception {
		CloseableHttpClient httpclient = null;
		if (StringUtils.startsWith(url, "https")) {
			httpclient = createSSLClientDefault();
		} else {
			httpclient = HttpClients.createDefault();
		}
		HttpPost httppost = new HttpPost(url);
		StringEntity entity = new StringEntity(jsonParams, "utf-8");
		entity.setContentType("application/json");
		entity.setContentEncoding("UTF-8");
		httppost.setEntity(entity);
		header.forEach((k, v) -> {
			httppost.setHeader(k, v);
		});

		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity1 = response.getEntity();
		String html = EntityUtils.toString(entity1, "UTF-8");
		httpclient.close();
		return html;
	}

}